package com.duobaoyu.chatwebsocket.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 钉钉错误消息通知
 *
 * @author ningchang
 */
@Component
@Slf4j
public class DingTalkUtil {

    @Value("${chat_web_hock}")
    private String webHock;

    @Value("${send_ding_switch}")
    private Boolean sendDingSwitch;

    /**
     * 钉钉群消息通知
     *
     * @param param 错误消息
     * @author ningchang
     */
    public void notify(String param) {
        if (sendDingSwitch) {
            HttpClient httpclient = HttpClients.createDefault();

            HttpPost httppost = new HttpPost(webHock);
            httppost.addHeader("Content-Type", "application/json; charset=utf-8");

            JSONObject textJson = new JSONObject();
            textJson.put("content", param.concat("yunvwugua"));
            JSONObject json = new JSONObject();
            json.put("msgtype", "text");
            json.put("text", textJson);

            StringEntity se = new StringEntity(json.toJSONString(), "utf-8");
            httppost.setEntity(se);

            try {
                HttpResponse response = httpclient.execute(httppost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String result = EntityUtils.toString(response.getEntity(), "utf-8");
                    log.info("send dingTalk message success,result:{}", result);
                }
            } catch (IOException e) {
                log.error("钉钉处理消息异常 param:" + param, e);
            }
        } else {
            log.error("钉钉消息开关关闭");
        }
    }
}
